package com.example.mybatis.util;

import com.example.init.SqltoyConfig;
import com.example.util.ConfigUtil;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.ibatis.datasource.pooled.PooledDataSource;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        SqltoyConfig sqltoyConfig = ConfigUtil.getConfig("mysql", SqltoyConfig.class);
        // 创建数据源
        PooledDataSource dataSource = new PooledDataSource(
                sqltoyConfig.getDriverClassName(),
                sqltoyConfig.getUrl(),
                sqltoyConfig.getUsername(),
                sqltoyConfig.getPassword()
        );

        // 创建事务工厂
        TransactionFactory transactionFactory = new JdbcTransactionFactory();

        // 创建环境
        Environment environment = new Environment.Builder("development")
                .transactionFactory(transactionFactory)
                .dataSource(dataSource)
                .build();

        // 创建Configuration对象
        Configuration configuration = new Configuration(environment);

        // 添加Mapper接口
        configuration.addMapper(com.example.mybatis.mapper.UserMapper.class);

        // 构建SqlSessionFactory
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}